#!/bin/bash

# ----------------------------------------------------------------------
# Filename:   ntp_restrict.sh
# Version:    1.0
# Date:       2013/11/13
# Author:     huijing.hei
# Email:      huijing.hei@cs2c.com.cn
# Summary:    02系统基本功能-04网络服务-11NTP-03搭建ntp服务器-02只允许特定网段的客户机进行时间同步
# Notes:       ***
# Copyright:    China Standard Software Co., Ltd.
# History：     
#             Version 1.0, 2013/11/13
#             - Start ntpd service, allow restrict ip to sync datetime.
# ----------------------------------------------------------------------

##! @TODO: start&stop http service
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function do_setup()
{
    trap do_cleanup INT EXIT
    serv=ntpd

    NTP_CONF=/etc/ntp.conf
    server_ip=`ifconfig -a | grep 'inet ' | grep -m 1 -v '127.0.0.1'  | awk '{print $2}' | tr -d "addr:"`

    server3=${server_ip%.*}

    # back ntp.conf
    [ -f ${NTP_CONF} ] && cp ${NTP_CONF} ${NTP_CONF}.bak
    EchoResult "backup ${NTP_CONF}"

    # setup ntp.conf
    # comment "server 0.rhel.pool.ntp.org";
    sed -i -e 's/^server [0|1|2|3].rhel.pool.ntp.org$/#&/g' ${NTP_CONF}
    grep -E "^server [0|1|2|3].rhel.pool.ntp.org" ${NTP_CONF}

    if [ $? -eq 0 ] ;then

        sed -i -e 's/^server [0|1|2|3].rhel.pool.ntp.org iburst$/#&/g' \
           ${NTP_CONF}
    fi

    ! grep -E "^server [0|1|2|3].rhel.pool.ntp.org" ${NTP_CONF}
    EchoResult "comment rhel ntp server"

    cat >> ${NTP_CONF} <<-EOF
server 127.127.1.0 # local clock
fudge 127.127.1.0 stratum 0
restrict ${server3}.0 mask 255.255.255.0 nomodify notrap
EOF


    # restart
    restart_daemon ${serv}
    EchoResult "service ${serv} restart"

    # check ntpd restart
    status_daemon ${serv}
    netstat -nlutp | grep ${serv}
    EchoResult "service ${serv} status: restart"


}

##! @TODO: test
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function do_test()
{
    ntpstat

    sleep 200

    ntpstat | grep "synchronised to local net at stratum 1"
    EchoResult "testcase: ${serv} allow restrict ip to sync datetime"
}

##! @TODO: cleanup
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure
function do_cleanup()
{
    mv -f ${NTP_CONF}.bak ${NTP_CONF}
    stop_daemon ${serv}

}

# include lib files

if [ -z "$SFROOT" ]
then
    CMDLIB=./
    SFROOT=./
else
    CMDLIB=${SFROOT}/testcases/Network_Service
fi

. ${SFROOT}/lib/Echo.sh
. ${CMDLIB}/lib/Net.sh

do_setup
do_test
